﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.ComponentModel;
using System.Windows.Markup;
using FTP = FTPSClient;

namespace Vision.Core.ActivityComponents.IO.Ftp
{
	[ContentProperty("Body")]
	[System.ComponentModel.Designer(typeof(FtpMakeDirectoryDesigner))]
	public sealed class FtpMakeDirectory : NativeActivity
	{
		internal FTP.FTPSClient FtpClient { get; set; }

		/// <summary>
		/// Gets or sets the file name to save as on the FTP site.
		/// </summary>
		[Category("Input")]
		public InArgument<string> DirectoryName { get; set; }

		/// <summary>
		/// Gets or sets the file name to save as on the FTP site.
		/// </summary>
		[Category("Input")]
		public InArgument<bool> SetAsCurrentDirectory { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[DefaultValue(null)]
		[Browsable(false)]
		public Activity Body { get; set; }

		/// <summary>
		/// Called when the activity is executed
		/// </summary>
		/// <param name="context"></param>
		protected override void Execute(NativeActivityContext context)
		{
			if (string.IsNullOrEmpty(this.DirectoryName.Get(context)))
				throw new ArgumentNullException("DirectoryName", "DirectoryName can not be null or an empty string.");

			this.FtpClient = (FTP.FTPSClient)context.Properties.Find("5AED2CE1-FB3C-45B3-9CB7-3DC8CD5E4C56");

			if (this.FtpClient != null)
			{
				try
				{
					this.FtpClient.MakeDir(this.DirectoryName.Get(context));
				}
				catch (Exception)
				{
					// occurs when the directory already exists, do nothing
					Console.WriteLine("Directory '{0}' already exists on the FTP site.", this.DirectoryName.Get(context));
				}

				if (this.SetAsCurrentDirectory.Get(context))
				{
					this.FtpClient.SetCurrentDirectory(this.DirectoryName.Get(context));
				}
			}

			// schedule the next activity
			if (this.Body != null)
				context.ScheduleActivity(this.Body);
		}
	}
}
